package com.flushbonading.classsystem.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.flushbonading.classsystem.entity.vo.LoginVO;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;

/**
 * @author zyx 2134208960@qq.com
 * @date 2021/11/10 20:40
 * @since 1.0.0
 */
public class JWTUtil {
    // 过期时间为1小时
    private static final long EXPIRE_TIME = 1*60*60*1000;
    // token私钥
    private static final String TOKEN_SECRET = "class_system";
    /**
     * 生成签名，1小时后过期
     * @param userId
     * @param password
     * @return
     */
    public static String sign(String userId, String password) throws UnsupportedEncodingException {
        // 过期时间
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        // 私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        // 设置头信息
        HashMap<String, Object> header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        // 附带username和userId生成签名
        return JWT.create().withHeader(header).withClaim("userId", userId)
                .withClaim("password", password).withExpiresAt(date).sign(algorithm);
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public static boolean verity(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (IllegalArgumentException e) {
            // TODO: handle exception
            return false;
        } catch (JWTVerificationException e) {
            // TODO: handle exception
            return false;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 解密
     * @param token
     * @return
     * @throws UnsupportedEncodingException
     */
    public static LoginVO deToken(String token) throws UnsupportedEncodingException {
        DecodedJWT jwt = null;
        jwt = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).build().verify(token);
        String userId = jwt.getClaim("userId").asString();
        String password = jwt.getClaim("password").asString();
        return LoginVO.builder().userId(userId).password(password).build();
    }

}
